package vn.tbs.kcdk;

import static vn.tbs.kcdk.global.Common.CATEGORY_ID_HISTORY;
import vn.tbs.kcdk.fragments.contents.media.ContentFragment;
import vn.tbs.kcdk.fragments.contents.media.MediaInfo;
import vn.tbs.kcdk.fragments.mediaplayer.KCDKMediaPlayer;
import vn.tbs.kcdk.fragments.menu.CategoryRow;
import vn.tbs.kcdk.fragments.menu.MenuFragment;
import vn.tbs.kcdk.fragments.timer.CloseTimer;
import vn.tbs.kcdk.global.Common;
import vn.tbs.kcdk.global.DrugsSearchAdapter;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnCloseListener;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class KCDKActivity  extends SlidingFragmentActivity implements OnOpenedListener, OnOpenListener, OnClosedListener, SearchView.OnQueryTextListener,
SearchView.OnSuggestionListener, OnCloseListener, OnFocusChangeListener, CloseTimer.OnFinishListener {

	private static final String TAG = KCDKActivity.class.getSimpleName();
	public static int THEME = R.style.Theme_MyAppTheme;
	private MenuFragment mMenuFragment;
	private Fragment mContentFragment;
	private SlidingMenu mSlidingMenu;
	private NavListAdapter mNavigationAdapter;
	public static Typeface sFont = null;
	private SearchView mSearchView;

	public static int sRemainSeconds = -1;
	
	public static CloseTimer sTimer;
	
	private static final String[] COLUMNS = {
		BaseColumns._ID,
		SearchManager.SUGGEST_COLUMN_TEXT_1,
	};

	private SuggestionsAdapter mSuggestionsAdapter;
	private View mPlayerNavigation;
	private boolean mEnableActionBar;

	//media player 
	public static KCDKMediaPlayer sKCDKMediaPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		//setTheme(THEME); //Used for theme switching in samples

		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate start");
		sFont=Typeface.createFromAsset(this.getAssets(),"Roboto-Light.ttf");
		setTitle(R.string.app_name);
		setAboveView(savedInstanceState);
		setBehindView();
		customizeSlidingMenu();
		mEnableActionBar = false;
		if (mEnableActionBar) {
			initActionBar();			
		}
		Log.i(TAG, "onCreate end");
	}

	private void initActionBar() {
		Log.i(TAG, "initActionBar start");

		//Inflate the custom view
		mPlayerNavigation = LayoutInflater.from(this).inflate(R.layout.media_player_panel_layout, null);
		//        View customNav = LayoutInflater.from(this).inflate(R.layout.download_media_controls, null);

		//Attach to the action bar
		getSupportActionBar().setCustomView(mPlayerNavigation);
		getSupportActionBar().setDisplayShowCustomEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		//init media player
		sKCDKMediaPlayer = new KCDKMediaPlayer(this,mPlayerNavigation);

		//customActionBar();
		//		startActionMode(new AnActionModeOfEpicProportions());

		Log.i(TAG, "initActionBar end");
	}


	private void customActionBar() {
		Log.i(TAG, "customActionBar start");


		// Generate title
		String[] title = new String[] { "Title Fragment 1", "Title Fragment 2",
		"Title Fragment 3" };

		// Generate subtitle
		String[] subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2",
		"Subtitle Fragment 3" };

		// Generate icon 
		int[] icon = new int[] { R.drawable.ic_fbcomment, R.drawable.ic_fblike,
				R.drawable.ic_launcher };

		// Pass results to NavListAdapter Class
		mNavigationAdapter = new NavListAdapter(this, title, subtitle, icon);

		// Hide the ActionBar Title
		getSupportActionBar().setDisplayShowTitleEnabled(false);

		// Create the Navigation List in your ActionBar
		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		// Listen to navigation list clicks
		ActionBar.OnNavigationListener navlistener = new OnNavigationListener() {

			@Override
			public boolean onNavigationItemSelected(int position, long itemId) {
				FragmentTransaction ft = getSupportFragmentManager()
						.beginTransaction();
				// Locate Position
				switch (position) {
				case 0:
					//					ft.replace(android.R.id.content, fragment1);
					break;
				case 1:
					//					ft.replace(android.R.id.content, fragment2);
					break;
				case 2:
					//					ft.replace(android.R.id.content, fragment3);
					break;
				}
				ft.commit();
				return true;
			}

		};
		// Set the NavListAdapter into the ActionBar Navigation
		getSupportActionBar().setListNavigationCallbacks(mNavigationAdapter, navlistener);		
		Log.i(TAG, "customActionBar end");
	}

	private void setBehindView() {
		Log.i(TAG, "setBehindView start");

		// set the Behind View
		setBehindContentView(R.layout.menu_frame);
		FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
		mMenuFragment = new MenuFragment();
		t.replace(R.id.menu_frame, mMenuFragment);
		t.commit();

		Log.i(TAG, "setBehindView end");
	}

	private void setAboveView(Bundle savedInstanceState) {
		Log.i(TAG, "setAboveView start");

		// load saved fragment
		Fragment fistFragment = null;
		if (savedInstanceState != null)
			fistFragment = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
		if (fistFragment == null){
			CategoryRow item = new CategoryRow(CATEGORY_ID_HISTORY, "History", false, null);
			fistFragment = Common.initContentFragment(item );

			/*Bundle bundle = Common.initFragmentBund(Common.FragmentMode.HISTORY, new String[]{"t2"});
			mContentFragment = new HistoryFragment();
			mContentFragment.setArguments(bundle);*/
		}

		// set the Above View
		setContentView(R.layout.content_frame);
		switchContent(fistFragment, true);
		//		getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContentFragment).commit();

		Log.i(TAG, "setAboveView end");
	}

	private void customizeSlidingMenu() {
		Log.i(TAG, "customizeSlidingMenu start");

		mSlidingMenu = getSlidingMenu();
		//		sm.setShadowWidthRes(R.dimen.shadow_width);
		//		sm.setShadowDrawable(R.drawable.shadow);
		mSlidingMenu.setShadowDrawable(null);
		mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		mSlidingMenu.setFadeDegree(0.35f);
		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		mSlidingMenu.setOnOpenedListener(this);
		mSlidingMenu.setOnOpenListener(this);
		mSlidingMenu.setOnClosedListener(this);
		mSlidingMenu.setFadeEnabled(true);

		//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setSlidingActionBarEnabled(false);


		Log.i(TAG, "customizeSlidingMenu end");
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.i(TAG, "onSaveInstanceState start");

		if (mContentFragment.isVisible()) {
			getSupportFragmentManager().putFragment(outState, "mContent", mContentFragment);			
		}

		Log.i(TAG, "onSaveInstanceState end");
	}

	public void switchContent(Fragment fragment, boolean addToBackStack) {
		Log.i(TAG, "switchContent start");

		if (mContentFragment!=fragment) {
			mContentFragment = fragment;
			FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
			Bundle bundle = fragment.getArguments();

			String tag = Common.NONE_VALUE;

			if (bundle!=null) {
				tag = bundle.getString(Common.FRAGMENT_TAG_KEY);				
			}
			transaction.replace(R.id.content_frame, fragment,tag );
			if (addToBackStack) {
				transaction.addToBackStack(tag);
			}

			transaction.commit();			
		}
		getSlidingMenu().showContent();		

		Log.i(TAG, "switchContent end");
	}

	@Override
	public void onClosed() {
		Log.i(TAG, "onClosed start");

		if (mContentFragment!=null&&mContentFragment instanceof ContentFragment) {
			((ContentFragment)mContentFragment).setHasOptionsMenu(true);
		}

//		showSearchView(null);

		Log.i(TAG, "onClosed end");
	}

	@Override
	public void onOpen() {
		Log.i(TAG, "onOpen start");

		if (mContentFragment!=null&&mContentFragment instanceof ContentFragment) {
			((ContentFragment)mContentFragment).setHasOptionsMenu(false);
		}

		Log.i(TAG, "onOpen end");
	}


	@Override
	public void onOpened() {
		Log.i(TAG, "onOpened start");

		if (mMenuFragment!=null) {
			mMenuFragment.refreshSelectedPosition(mContentFragment);			
		}

		Log.i(TAG, "onOpened end");
	}

	public void setmContentFragment(Fragment mContentFragment) {
		this.mContentFragment = mContentFragment;
	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy start");

		if (sKCDKMediaPlayer!=null) {
			sKCDKMediaPlayer.stop();
			sKCDKMediaPlayer = null;
		}
		super.onDestroy();

		Log.i(TAG, "onDestroy end");
	}


	public void showMediaPageById(MediaInfo media) {
		Log.i(TAG, "showMediaPageById start");

		String mediaId = media.getMediaId();

		if (mediaId !=null&&mediaId.length()>0) {

			FragmentManager fm = getSupportFragmentManager();
			Fragment fg = fm.findFragmentByTag(mediaId);
			if (fg!=null) {
				fm.popBackStack(mediaId,0);
			}
			else{
				Common.showMediaContent(media ,this);
			}

			if (mSlidingMenu!=null) {
				mSlidingMenu.showContent();
			}
		}

		Log.i(TAG, "showMediaPageById end");
	}

	public Fragment findFragmentByTag(String tag) {
		Log.i(TAG, "findFragmentByTag start");

		FragmentManager fm = getSupportFragmentManager();
		Fragment fg = fm.findFragmentByTag(tag);

		Log.i(TAG, "findFragmentByTag end");
		return fg;

	}

	public void setMenuVisible(boolean isShow) {
		Log.i(TAG, "hideMenuView start");

		if (mNavigationAdapter!=null) {
			mNavigationAdapter.setMenuVisible(isShow);
		}

		Log.i(TAG, "hideMenuView end");
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show();
		Log.i(TAG, "onQueryTextSubmit query "+query);

		mMenuFragment.showFoundMediaFragment(query,(CategoryRow) mSearchView.getTag());
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
		
		mSearchView.setQuery("", false);
		//		mSearchView.clearFocus();
		return true;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		return false;
	}

	@Override
	public boolean onSuggestionSelect(int position) {
		return false;
	}

	@Override
	public boolean onSuggestionClick(int position) {
		Cursor c = (Cursor) mSuggestionsAdapter.getItem(position);
		String query = c.getString(c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
		Toast.makeText(this, "Suggestion clicked: " + query, Toast.LENGTH_LONG).show();
		return true;
	}

	@Override
	public void onFocusChange(View view, boolean queryTextFocused) {
		if(!queryTextFocused) {
			getSupportActionBar().setCustomView(mPlayerNavigation);				
			getSlidingMenu().showContent(true);
		}
	}

	@Override
	public boolean onClose() {
		Log.i(TAG, "onClose start");
		//		showSearchView(false);
		return false;

	}
	private class SuggestionsAdapter extends CursorAdapter {

		public SuggestionsAdapter(Context context, Cursor c) {
			super(context, c, 0);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
			return v;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView tv = (TextView) view;
			final int textIndex = cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
			tv.setText(cursor.getString(textIndex));
		}
	}

	public void showSearchView(CategoryRow item) {
		if (item!=null) {
			initSearchView();
			getSupportActionBar().setCustomView(mSearchView);
			mSearchView.requestFocus();
			mSearchView.setTag(item);
			
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);			
		}
	}

	private void initSearchView() {
		Log.i(TAG, "initSearchView start");

		if (mSearchView==null) {

			//Create the search view
			mSearchView = new SearchView(this){

			};
			mSearchView.setIconifiedByDefault(false);
			mSearchView.setQueryHint("nhap text");
			mSearchView.setOnQueryTextListener(this);
			mSearchView.setOnSuggestionListener(this);
			mSearchView.setOnCloseListener(this);
			mSearchView.setOnQueryTextFocusChangeListener(this);

			if (mSuggestionsAdapter == null) {
				MatrixCursor cursor = new MatrixCursor(COLUMNS);
				cursor.addRow(new String[]{"1", "'Murica"});
				cursor.addRow(new String[]{"2", "Canada"});
				cursor.addRow(new String[]{"3", "Denmark"});
				mSuggestionsAdapter = new SuggestionsAdapter(this, cursor);
			}

			SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
			// Tells your app's SearchView to use this activity's searchable configuration
			mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
			mSearchView.setSuggestionsAdapter(new DrugsSearchAdapter(this, searchManager.getSearchableInfo(getComponentName()), mSearchView));

			//			mSearchView.setSuggestionsAdapter(mSuggestionsAdapter);
		}
	}

	@Override
	public void onBackPressed() {
		if (getSupportActionBar()!=null&&getSupportActionBar().getCustomView()!=null&&getSupportActionBar().getCustomView().equals(mSearchView)) {
			getSupportActionBar().setCustomView(mPlayerNavigation);
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
		}
		super.onBackPressed();
	}

	public void showPlayer() {
		if (getSupportActionBar()!=null) {
			getSupportActionBar().setCustomView(mPlayerNavigation);
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(mPlayerNavigation.getWindowToken(), 0);			
		}
	}

	@Override
	public void doFinish() {
		Log.i(TAG, "doFinish start");
		
		finish();
		
		Log.i(TAG, "doFinish end");
	}

}
